const BASE_URL = 'http://127.0.0.1:3000/api';

let httpCount: number = 0
const request = ({
    url, 
    method, 
    params, 
    data, 
	headers
}: {
	url: string,
	method: 'POST' | 'GET', 
	params?: any, 
	data?: any,
	headers?: any
}) => {
    return new Promise((resolve, reject) => {
		console.log('httpCount', httpCount)
		if(httpCount === 0) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})			
		}
		httpCount++
		
        const token = uni.getStorageSync('token');
		if(token) {
			headers['Authorization'] = token;
		}
        uni.request({
            url: BASE_URL + url,
            data: method === 'GET' ? params : data,
            method: method,
            header: headers,
            success: (res) => {
				// TODO 根据接口调整
                const { code, message } = res.data;
				
				httpCount--
				if(httpCount === 0) {
					uni.hideLoading();
				}
				
                if (code === 200) {
                    return resolve(data);
                } else {
					uni.showToast({
					    icon: 'none',
					    duration: 3000,
					    title: '请求失败，请稍后重试！',
					});
					return reject(data);
				}
            },
            fail(error) {
				if(httpCount > 0) {
					httpCount--
				}
				if(httpCount === 0) {
					uni.hideLoading();
				}
				
                console.log('请求错误：', error);
                uni.showToast({
                    icon: 'none',
                    duration: 3000,
                    title: '网络异常，请稍后重试！',
                });
                return reject(error);
            },
            complete() {},
        });
    });
};

export default request;